#/usr/bin/env python3
import os
from src.http_protocol import HttpProtocol

class ListDir:
    def __init__(self, server_dirs):
        self.hp = HttpProtocol()
        self.s_dirs = server_dirs

    def list_childs(self, cur_dir, show_hidden = False):
        dlist = []
        flist = []
        for f in os.listdir(cur_dir):
            file_path = os.path.join(cur_dir, f)
            if os.path.isdir(file_path):
                dlist.append(file_path)
            else:
                if show_hidden:
                    flist.append(file_path)
                elif f[0] != '.':
                    flist.append(file_path)
        return (dlist, flist)


    def file_exists(self, req_url):
        return os.path.isfile(req_url)

    def dir_exists(self, req_url):
        return os.path.isdir(req_url)

    def is_exists(self, dirs, req_url):
        for d in dirs:
            file_path = os.path.join(d, req_url)
            if os.path.isfile(file_path):
                return True
        return False

    def get_page(self, url = "/", cur_d = None):
        l_content = ""
        if url == "/":
            for d in self.s_dirs:
                dirname = d[d.rfind("/")+1:]
                dirname = dirname.replace("/", "")
                l_content += "<li><a href=/" + dirname +">" + dirname + "</a></li>"
        else:
            dirname = cur_d[:cur_d.rfind("/")]
            server_dir_index = len(dirname)
            l_content = "<li><a href="+url[server_dir_index:]+">.</a></li>"
            parent_dir = os.path.abspath(os.path.join(url, ".."))
            if dirname == parent_dir:
                l_content += "<li><a href=/>..</a></li>"
            else:
                l_content += "<li><a href="+ parent_dir[server_dir_index:] +">..</a></li>"
            dlist, flist = self.list_childs(url)
            for dd in dlist:
                l_content += "<li><a href=" + dd[server_dir_index:] +">" + dd[dd.rfind("/")+1:] + "</a></li>"
            for f in flist:
                l_content += "<li><a href=" + f[server_dir_index:] +">" + f[f.rfind("/")+1:] + "</a></li>"
        content = '''<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head><body><h3 style="font-size:2pc">'''+ l_content+'''</h3></body></html>'''
        encode_content = content.encode("utf-8")
        response_content = self.hp.get_header(200, "text", len(encode_content), len(encode_content)).encode("utf-8") + encode_content
        return response_content

if __name__ == "__main__":
    ld = ListDir()
    d, f = ld.list_childs("/home/zach/Desktop", True)
    print(d)
    print(f)


